package logic

import (
	"context"
	"fmt"
	"lucky/cache"
	"lucky/models"

	"lucky/luckyrpc/internal/svc"
	"lucky/luckyrpc/luckyrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *luckyrpc.CartAddRequest) (*luckyrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var product models.Product
	err := models.DB.Debug().Where("id = ?", in.ProductId).Find(&product).Error
	if err != nil {
		return nil, fmt.Errorf("当前商品不存在")
	}

	if in.Quantity > 200 {
		return nil, fmt.Errorf("单次购买不得大于200")
	}

	if in.Quantity > product.Stock {
		return nil, fmt.Errorf("当前商品库存不足")
	}

	if cache.IsExistCartProduct(in.UserId, in.ProductId) {
		err = cache.UpdateCartQuantity(in.UserId, in.ProductId, int(in.Quantity))
		if err != nil {
			return nil, fmt.Errorf("商品库存更新失败")
		}
	} else {
		productMap := map[string]interface{}{
			"userId":     in.UserId,
			"productId":  in.ProductId,
			"quantity":   in.Quantity,
			"name":       product.Name,
			"price":      product.Price,
			"stock":      product.Stock,
			"ingredient": product.Ingredient,
			"taste":      product.Taste,
			"status":     product.Status,
			"imageUrl":   product.ImageUrl,
			"category":   product.Category,
		}
		err = cache.CartAdd(int(in.UserId), in.ProductId, productMap)
		if err != nil {
			return nil, fmt.Errorf("购物车添加失败")
		}
	}

	return &luckyrpc.CartAddResponse{
		Success: true,
		Message: "购物车添加成功",
	}, nil
}
